package com.yoga.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Set;
import java.util.UUID;

/**
 * @author yan
 * @date 2025/8/15
 */
@Component
public class AliOSS {
    @Value("${aliyun.oss.endpoint}")
    private String endpoint;
    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;
    @Value("${aliyun.oss.bucketName}")
    private String bucketName;

    public String upload(MultipartFile file,String type) throws IOException {
        System.out.println("接收到文件: " + file.getOriginalFilename());
        System.out.println("指定目录类型: " + type);
        //获取文件输入流
        InputStream inputStream = file.getInputStream();
        //白名单校验
        if (!isValidImage(file.getOriginalFilename())) {
            throw new RuntimeException("文件格式错误");
        }
        //限制大小
        if (file.getSize() > 1024 * 1024 * 5) {
            throw new RuntimeException("文件大小不可超过5MB");
        }
        String fileName = file.getOriginalFilename();
        String newName = UUID.randomUUID().toString() + fileName.substring(fileName.lastIndexOf("."));
        String objectKey;
        if (type != null && !type.isEmpty()) {
            // 确保目录以 / 结尾
            if (!type.endsWith("/")) {
                type += "/";
            }
            objectKey = type + newName;
        } else {
            objectKey = newName;
        }
        //创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ossClient.putObject(bucketName, objectKey, inputStream);
        ossClient.shutdown();
        // 更安全的URL构建方式
        String endpointHost = endpoint.replace("https://", "");
        String url = String.format("https://%s.%s/%s", bucketName, endpointHost, objectKey);
        System.out.println( url);
        return url;
    }

    //白名单校验法
    private boolean isValidImage(String fileName) {
        Set<String> allowedExt = Set.of(".jpg", ".png", ".jpeg", ".gif");
        String ext = getFileExt(fileName);
        return allowedExt.contains(ext);
    }

    private String getFileExt(String fileName) {
        if (fileName == null || fileName.lastIndexOf(".") == -1) {
            return "";
        }
        return fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
    }
}
